package com.example.websocketdemo.controller;

import com.example.websocketdemo.dao.UserMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * TODO   设置text/event-stream 进行消息推送返回
 *        UDP 接收和发送的方法
 *
 * @ClassName UserController
 * @Author xiaojiang
 * @Date 2021/9/29 下午 17:22
 */
@RestController
public class UserController {

    private Logger logger = LoggerFactory.getLogger(UserController.class);

    @Autowired
    private UserMapper userMapper;

    /**
     *  TODO  查询所有用户名
     * @Param : a
     * @return String
     * @Author 江
     * @Date 2021/9/29 下午 17:23
     */
    @RequestMapping("/getAllUser")
    public String getAllUser(){
        logger.info("进入接口：---");

        logger.info("准备返回消息：---");
        return  userMapper.getAllUser();

    }

    /**
     *  TODO  测试推送返回
     * @Param : request
     * @Param : resp
     * @return void
     * @Author 江
     * @Date 2021/9/29 下午 17:24
     */
    @RequestMapping("/getTest")
    public void getTest(HttpServletRequest request, HttpServletResponse resp) throws IOException {
        resp.setContentType("text/event-stream;charset=utf-8");
        PrintWriter out = resp.getWriter();
        for (int i = 0; i < 10; i++) {
            String allUser = userMapper.getAllUser();
            out.write("data: UserName:" + allUser + i+"\n\n");
            out.flush();
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    @RequestMapping("/getTestSEE")
    public String getTestSEE(){
        return  "hello";
    }

    /**
     *  TODO   AMF1 向 AMF2 发送的 InterReg 启动或者停止的 UDP 消息
     * @Author 江
     * @Date 2021/10/13 下午 12:32
     */
    public void sendInterRegENDPDU(String AMF2IP, byte[] data) {
        logger.info("准备向发送 AMF2 InterReg 消息=");
        DatagramSocket datagramSocket = null;
        try {
            // 实例化套接字，并指定发送端口
            datagramSocket = new DatagramSocket();
            // 指定数据目的地的地址，以及目标端口
            InetAddress destination = InetAddress.getByName(AMF2IP);
            DatagramPacket datagramPacket = new DatagramPacket(data, data.length, destination, 40201);
            // 发送数据
            datagramSocket.send(datagramPacket);
            logger.info("发送AMF2 InterReg 启动或停止消息已发送=");
        } catch (SocketException e) {
            logger.info("发送AMF2 InterReg 启动或停止 消息发送失败=", e);

        } catch (IOException e) {
            logger.info("发送AMF2 InterReg 启动或停止 消息发送失败-", e);
        } finally {
            datagramSocket.close();
        }
    }

    private ExecutorService udpServerThread = Executors.newFixedThreadPool(20);
    /**
     *  TODO   AMF2 接收 AMF1 发送的 InterReg 启动或者停止的UDP消息
     * @Author 江
     * @Date 2021/10/13 下午 12:32
     */
    private static boolean InterRegStatusUdpServerFlag = false;
    private void startInterRegUdpServer() {
        udpServerThread.submit(new Runnable() {
            @Override
            public void run() {
                DatagramSocket datagramSocket = null;
                try {
                    datagramSocket = new DatagramSocket(40201);
                } catch (SocketException e1) {
                    logger.error("create socket error", e1);
                    return;
                }
                InterRegStatusUdpServerFlag = true;
                logger.info("server:connecting...");
                try {
                    while (true) {
                        byte[] buf = new byte[2048];
                        DatagramPacket datagramPacket = new DatagramPacket(buf, 0, buf.length);
                        datagramSocket.receive(datagramPacket);
                        String data = new String(datagramPacket.getData(), 0, datagramPacket.getLength());
                        logger.info("AMF2  InterReg 的 UDP接收 AMF1 的数据:" + data);
                        if ("1".equals(data)) {

                        } else if ("3".equals(data)) {

                        } else {
                            logger.warn("UDP接收 AMF1 InterReg 启动或者停止的数据错误!");
                        }
                        datagramPacket = null;
                        buf = null;
                    }
                } catch (Exception e) {
                    logger.info("server: Error!", e);
                }
                datagramSocket.close();
            }
        });
    }

    /**
     *  TODO  UDP 测试接收
     * @Author 江
     * @Date 2021/10/13 下午 15:55
     */
    public static void main(String[] args) {
        DatagramSocket datagramSocket = null;
        try {
            datagramSocket = new DatagramSocket(40100);
        } catch (SocketException e1) {
            System.out.println();
            System.out.println("create socket error" + e1);
            return;
        }
        System.out.println("server:connecting...");
        try {
            while (true) {
                byte[] buf = new byte[2048];
                DatagramPacket datagramPacket = new DatagramPacket(buf, 0, buf.length);
                datagramSocket.receive(datagramPacket);
                String data = new String(datagramPacket.getData(), 0, datagramPacket.getLength());
                System.out.println("UDP 接收 AMF1 的数据:" + data);
                String imsi = data.substring(0, data.indexOf("/"));
                System.out.println("imsi = " + imsi);
                String random = data.substring(data.indexOf("/") + 1, data.indexOf("+"));
                System.out.println("random = " + random);
                String type = data.substring(data.indexOf("+") + 1, data.length());
                System.out.println("type = " + type);
//                        handleMessage(datagramPacket);    // 调用方法
                datagramPacket = null;
                buf = null;
            }
        } catch (Exception e) {
            System.out.println("server: Error!" + e);
        }
        datagramSocket.close();
    }


}
